<!-- 产品碳足迹-产品碳足迹-产品核算-模型搭建-工序表单 -->

<template>
  <div>
    <div class="table-page-search-wrapper">
      <a-form-model :model="formObj" layout="vertical">
        <a-form-model-item :label="$t('message.Process_name')" required>
          <a-input
            v-model="formObj.processName"
            :disabled="disabled"
            allowClear
            :placeholder="$t('message.Please_enter')"
          ></a-input>
        </a-form-model-item>
        <a-collapse v-model="activeCollapseKey" :bordered="false">
          <template #expandIcon="props">
            <img
              class="collapseIcon"
              src="@assets/img/img47.png"
              alt=""
              v-if="props.isActive"
            />
            <img
              class="collapseIcon"
              src="@assets/img/img46.png"
              alt=""
              v-else
            />
          </template>
          <a-collapse-panel
            :key="String(artifactIndex)"
            :header="
              artifactIndex === 0
                ? $t('message.The_things_produced')
                : $t('message.By_product')
            "
            v-for="(artifactItem, artifactIndex) in formObj.outputList"
          >
            <!--              <a-popconfirm title="删除副产物?" cancelText="取消" okText="确定"-->
            <!--                            @confirm="() => onDelArtifact(artifactIndex)" v-if="artifactIndex > 0">-->
            <!--                <img slot="extra" class="collapseIcon" src="@assets/img/img33.png" alt=""/>-->
            <!--              </a-popconfirm>-->
            <img
              slot="extra"
              class="collapseIcon"
              src="@assets/img/img33.png"
              alt=""
              @click="onDelArtifact(artifactIndex)"
              v-if="artifactIndex > 0"
            />
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-model-item :label="$t('message.Name')" required>
                  <a-input
                    v-model="artifactItem.artifactName"
                    :disabled="disabled"
                    allowClear
                    :placeholder="$t('message.Please_enter')"
                  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item
                  :label="`${$t('message.Proportion')}（%）`"
                  required
                >
                  <a-input-number
                    v-model="artifactItem.artifactProportion"
                    :step="0.01"
                    :precision="2"
                    :disabled="true"
                    :max="100"
                    :placeholder="$t('message.Please_enter')"
                    style="width: 100%"
                    v-if="artifactIndex === 0"
                  ></a-input-number>
                  <a-input-number
                    v-model="artifactItem.artifactProportion"
                    :step="0.01"
                    :precision="2"
                    :disabled="disabled"
                    :min="0"
                    :max="100"
                    :placeholder="$t('message.Please_enter')"
                    style="width: 100%"
                    v-else
                  ></a-input-number>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-model-item :label="$t('message.Number')" required>
                  <a-input-number
                    v-model="artifactItem.artifactNumber"
                    :disabled="disabled"
                    :placeholder="$t('message.Please_enter')"
                    :step="0.01"
                    :precision="2"
                    style="width: 100%"
                  ></a-input-number>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item :label="$t('message.Unit')" required>
                  <a-select
                    v-model="artifactItem.artifactUnit"
                    :disabled="disabled"
                    allowClear
                    :placeholder="$t('message.Please_select')"
                    @change="onChangeArtifactUnit($event, artifactItem)"
                  >
                    <a-select-opt-group
                      :key="key"
                      :value="key"
                      :label="key"
                      v-for="(value, key, index) in getAllUnitByGroupData"
                    >
                      <a-select-option
                        :key="itemA.id"
                        :value="itemA.id"
                        v-for="(itemA, indexA) in value"
                      >
                        {{ itemA.unitCode }}
                      </a-select-option>
                    </a-select-opt-group>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
        <div class="addBtn m_hoverCP" @click="onAddArtifact" v-if="!disabled">
          <img class="addBtn_icon" src="@assets/img/img30.png" alt="" />{{
            $t("message.Add_by_product")
          }}
        </div>
      </a-form-model>
      <div class="drawerOptionBox">
        <a-button @click="onSave">{{ $t("message.Save") }}</a-button>
        <a-button
          type="primary"
          style="margin-left: 8px"
          @click="onSubmit"
          v-if="!disabled"
        >
          {{ $t("message.Next_add_the_emission_sources") }}</a-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import { getAction, postAction } from "@/api/manage";
import { cloneObject } from "@/utils/util";

export default {
  name: "processForm",
  components: {},
  props: {
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      visible: false,
      drawerTitle: "",
      formObj: {
        // 产出物数据,第一条为主产出物，其他为副产出物
        outputList: [{}],
      },
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      activeCollapseKey: ["0"],
      getAllUnitByGroupData: {}, // 单位分组数据
      type: 1, //1  新建  2编辑,
      CopyIasss: false, //fasle 不复制
    };
  },
  watch: {
    "formObj.outputList": {
      deep: true,
      immediate: true,
      handler(val, val2) {
        console.log("watch formObj.outputList =>", val, val2);
        if (val && val.length > 1) {
          let data = val.slice(1, val.length);
          let artifactProportion = 100;
          data.forEach((item) => {
            if (item.artifactProportion && Number(item.artifactProportion)) {
              artifactProportion = artifactProportion - item.artifactProportion;
            }
          });
          this.formObj.outputList[0].artifactProportion = artifactProportion;
        } else {
          this.formObj.outputList[0].artifactProportion = 100;
        }
      },
    },
  },
  created() {},
  methods: {
    /**
     * 添加副产出物
     */
    onAddArtifact() {
      this.formObj.outputList.push({
        artifactName: "",
        artifactProportion: "",
        artifactNumber: "",
        artifactUnit: "",
      });
      let data1 = this.formObj.outputList.length - 1;
      this.activeCollapseKey.push(String(data1));
      console.log("onAddArtifact", this.activeCollapseKey);
    },
    /**
     * 删除副产出物
     * @param artifactIndex
     */
    onDelArtifact(artifactIndex) {
      this.formObj.outputList.splice(artifactIndex, 1);
    },
    /**
     * 修改单位
     */
    onChangeArtifactUnit(e, artifactItem) {
      console.log("onChangeArtifactUnit", e, this.getAllUnitByGroupData);
      for (let key in this.getAllUnitByGroupData) {
        let value = this.getAllUnitByGroupData[key];
        for (let index = 0; index < value.length; index++) {
          if (value[index].id == e) {
            artifactItem.artifactUnitName = value[index].unitCode;
          }
        }
      }
    },
    /**
     * 检查工序表单数据
     */
    checkFormData() {
      if (!this.formObj.processName) {
        // this.$message.warn('请输入工序名称')
        this.$message.warn(this.$t("message.please_enter_operation_name"));
        return false;
      }
      console.log("检查工序表单数据");
      let errName = null;
      let errIndex = null;
      for (let i = 0; i < this.formObj.outputList.length; i++) {
        let obj = this.formObj.outputList[i];
        console.log("obj", obj);

        if (!obj.artifactName) {
          errIndex = i;
          if (errIndex === 0) {
            // errName = '产出物名称'
            errName = this.$t("message.please_enter_name");
          } else {
            // errName = `#${i}副产出物名称`
            errName = this.$t("message.please_enter_name");
          }
          break;
        }
        if (
          !obj.artifactProportion &&
          obj.artifactProportion !== 0 &&
          obj.artifactProportion !== "0"
        ) {
          errIndex = i;
          if (errIndex === 0) {
            // errName = '产出物占比'
            errName = this.$t("message.please_enter_proportion");
          } else {
            // errName = `#${i}副产出物占比`
            errName = this.$t("message.please_enter_proportion");
          }
          break;
        }
        if (!obj.artifactNumber) {
          errIndex = i;
          if (errIndex === 0) {
            // errName = '产出物数量'
            errName = this.$t("message.please_enter_number");
          } else {
            // errName = `#${i}副产出物数量`
            errName = this.$t("message.please_enter_number");
          }
          break;
        }
        if (!obj.artifactUnit) {
          errIndex = i;
          if (errIndex === 0) {
            // errName = '产出物单位'
            errName = this.$t("message.please_select_unit");
          } else {
            // errName = `#${i}副产出物单位`
            errName = this.$t("message.please_select_unit");
          }
          break;
        }
      }
      if (errIndex !== null) {
        // this.$message.warn(`请输入${errName}`)
        this.$message.warn(errName);
        return false;
      }
      if (this.formObj.outputList[0].artifactProportion < 0) {
        // this.$message.warn('产出物占比不能小于0')
        this.$message.warn(
          this.$t("message.output_proportion_cannot_be_less_than_0")
        );
        return false;
      }
      return true;
    },
    /**
     * 保存工序数据
     */
    onSave() {
      console.log("onSubmit", this.formObj, this.CopyIasss);
      if (this.type == 1) {
        if (this.checkFormData()) {
          let reqData = cloneObject(this.formObj);
          reqData.outputList.forEach((item, index) => {
            item.sort = index + 1;
          });
          if (this.CopyIasss) {
            reqData.emissionList = this.formObj.emissionDetailList;
          }
          postAction(
            "/CyWorkmanshipLibrary/cyWorkmanshipLibrary/add",
            reqData
          ).then((res) => {
            if (res.success) {
              this.$message.success(this.$t("message.operation_success"));
              this.type = 2;
              this.formObj.id = res.result;
            } else {
              this.$message.warn(res.message);
            }
          });
        }
      } else {
        if (this.checkFormData()) {
        let reqData = cloneObject(this.formObj);
        reqData.outputList.forEach((item, index) => {
          item.sort = index + 1;
        });
        postAction(
          "CyWorkmanshipLibrary/cyWorkmanshipLibrary/edit",
          reqData
        ).then((res) => {
          if (res.success) {
            this.$message.success(this.$t("message.operation_success"));
            // this.onClose();
          } else {
            this.$message.warn(res.message);
          }
        });
      }
      }
    },
    /**
     * 提交工序数据
     */
    onSubmit() {
      console.log("onSubmit", this.formObj);
      if (this.type == 1) {
        if (this.checkFormData()) {
          let reqData = cloneObject(this.formObj);
          reqData.outputList.forEach((item, index) => {
            item.sort = index + 1;
          });
          if (this.CopyIasss) {
            reqData.emissionList = this.formObj.emissionDetailList;
          }
          postAction(
            "/CyWorkmanshipLibrary/cyWorkmanshipLibrary/add",
            reqData
          ).then((res) => {
            if (res.success) {
              this.$message.success(this.$t("message.operation_success"));
              this.$emit("changeStep", 2, res.message);
              this.onClose();
            } else {
              this.$message.warn(res.message);
            }
          });
        }
      } else {
        if (this.checkFormData()) {
          let reqData = cloneObject(this.formObj);
          reqData.outputList.forEach((item, index) => {
            item.sort = index + 1;
          });
          postAction(
            "CyWorkmanshipLibrary/cyWorkmanshipLibrary/edit",
            reqData
          ).then((res) => {
            if (res.success) {
              this.$message.success(this.$t("message.operation_success"));
              this.$emit("changeStep", 2, reqData.id);
              this.onClose();
            } else {
              this.$message.warn(res.message);
            }
          });
        }
      }
    },
    getData() {
      // 单位
      getAction("/emission/factor/cyEmissionUnit/getAllUnitByGroup").then(
        (res) => {
          if (res.success) {
            this.getAllUnitByGroupData = res.result || {};
          }
        }
      );
    },
    onType(value) {
      this.type = value;
    },
    queryById(value, type) {
      console.log(value, type, "queryById");
      getAction("/CyWorkmanshipLibrary/cyWorkmanshipLibrary/queryById", {
        id: value,
      }).then((res) => {
        if (res.success) {
          if (type) {
            this.type = type;
          } else {
            this.type = 1;
          }
          console.log(this.type, "queryById");
          this.formObj = res.result || {};
          this.formObj.outputList = res.result.outPutList;
          this.formObj.outputList.forEach((item, index) => {
            this.activeCollapseKey.push(String(index));
          });
        }
      });
    },
    // ==============================================================================
    /**
     * 下拉框数据过滤
     */
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    /**
     * 关闭抽屉，初始化数据
     */
    onClose() {
      this.formObj = {
        outputList: [{}], // 产出物数据,第一条为主产出物，其他为副产出物
      };
      this.visible = false;
    },
  },
};
</script>

<style lang="less" scoped>
/deep/ .ant-collapse-content > .ant-collapse-content-box {
  padding: 16px 24px 0;
}

/deep/ .ant-collapse > .ant-collapse-item {
  border-bottom: none;
}

/deep/ .ant-collapse {
  background: #fff;
}

/deep/ .ant-collapse-item {
  margin-bottom: 16px;
}

/deep/ .ant-collapse-header {
  background: #f5f7f6;
}

/deep/ .ant-collapse-content {
  background: #f5f7f6;
}

/deep/ .ant-collapse-content-box {
  background: #f5f7f6;
}

.table-page-search-wrapper {
  position: relative;
  padding-bottom: 64px;
}

//
///deep/ .table-page-search-wrapper .ant-form-inline .ant-form-item {
//  margin-bottom: 44px;
//}
//
///deep/ .ant-form-item {
//  margin-bottom: 44px;
//}

.collapseIcon {
  width: 16px;
  height: 16px;
}

.delIcon {
  width: 22px;
  height: 22px;
}

.addBtn {
  margin-top: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: fit-content;
  padding: 5px 16px;
  background: #ffffff;
  border-radius: 3px;
  border: 1px solid #148958;
  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: #148958;

  .addBtn_icon {
    width: 16px;
    height: 16px;
  }
}

.drawerOptionBox {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e9e9e9;
  padding: 10px 16px;
  background: #fff;
  text-align: center;
  z-index: 1;
}
</style>
